//
//  CZEmoticonKeyboard.swift
//  61.新工程表情键盘
//
//  Created by apple on 16/3/7.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 表情键盘的view
class CZEmoticonKeyboard: UIView {
    
    // MARK: - 属性
    weak var textView: UITextView?
    
    private let ReuseIdentifier = "ReuseIdentifier"
    
    // 布局
    private let layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        prepareUI()
    }
    
    /**
     准备UI
     */
    private func prepareUI() {
        // 1.添加子控件
        addSubview(collectionView)
        addSubview(toolBar)
        addSubview(pageControl)
        
        // 2.设置约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        // VFL
        // collectionView 水平
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: ["cv" : collectionView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: ["tb" : toolBar]))
        
        // 垂直
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView, "tb": toolBar]))
        
        // pageContrl
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 25))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 设置collectionView cell的大小
        layout.itemSize = collectionView.frame.size
        
        
    }
    // MARK: - 懒加载
    // collectionView
    private lazy var collectionView: UICollectionView = {
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
        
        // 注册cell
        cv.registerClass(CZEmoticonPageCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        cv.delegate = self
        cv.dataSource = self
        cv.bounces = false
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        cv.backgroundColor = UIColor.clearColor()

        self.layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        self.layout.minimumLineSpacing = 0

        return cv
    }()
    
    // toolBar
    private lazy var toolBar: CZEmoticonToolBar = {
        let bar = CZEmoticonToolBar.emoticonToolBar()
        bar.delegate = self
        return bar
    }()
    
    // pageControl
    private lazy var pageControl: UIPageControl = {
        let control = UIPageControl()
        
        // 不能使用图片来平铺
//        control.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
//        control.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        
        // 想直接给pageControl设置背景图片
        // 需要找到pageControl里面不对外公开的属性,runtime
        // runtime重要的关键字: class objc
//        UIPageControl.printIvars()
        // 使用KVC给属性赋值
        control.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        control.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return control
    }()
}

// MARK: - 扩展CZEmoticonKeyboard 实现 CZEmoticonToolBarDelegate
extension CZEmoticonKeyboard: CZEmoticonToolBarDelegate {
    func toolBarButtonClick(type: CZEmoticonToolBarType) {
        // 滚动到的indexPath
        let indexPath: NSIndexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)

        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        // 设置pageControl
        setupPageControl(indexPath)
    }
}

// MARK: - 扩展CZEmoticonKeyboard 实现UICollectionViewDataSource和UICollectionViewDelegate
extension CZEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    /// collectionView显示的组数,一个表情包显示一组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonManager.sharedManager.emoticonPackages.count
    }
    
    /// 每个表情包里面的表情的页数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonManager.sharedManager.emoticonPackages[section].pageEmoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! CZEmoticonPageCell
        
//        cell.backgroundColor = UIColor.randomColor()
        cell.indexPath = indexPath
        
        // 将对应这页需要显示的表情模型数组传递给cell
        cell.pageEmoticons = CZEmoticonManager.sharedManager.emoticonPackages[indexPath.section].pageEmoticons[indexPath.item]
        
        // 4.成为代理
        cell.delegate = self
        
        return cell
    }
    
    // 监听scrollView的滚动.来判断该显示哪个section
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 获取中心点
        var referencePoint = scrollView.center
        referencePoint.x += scrollView.contentOffset.x
        
        // 获取所有正在显示cell的indexPath
        let indexPaths = collectionView.indexPathsForVisibleItems()
        
        // 遍历所有正在显示cell的indexPath
        for indexPath in indexPaths {
            // 通过indexPath获取正在cell
            let cell = collectionView.cellForItemAtIndexPath(indexPath)
            
            // 判断中心点是否在cell的frame里面
            if CGRectContainsPoint(cell!.frame, referencePoint) {
                // 包含,找到了
                
//                print("包含,找到了indexPath: \(indexPath.section)")
                
                // 让toolBar对应的按钮选中
                toolBar.switchSelectButtonWitchSelectSection(indexPath.section)
                
                setupPageControl(indexPath)
                break
            }
        }
    }
    
    /**
     设置pageControl的numberOfPages和currentPage
     
     - parameter indexPath:
     */
    private func setupPageControl(indexPath: NSIndexPath) {
        // 设置pageControl的页数和当前页
        pageControl.numberOfPages = CZEmoticonManager.sharedManager.emoticonPackages[indexPath.section].pageEmoticons.count
        pageControl.currentPage = indexPath.item
        
        // 判断如果section == 0 pageControl不需要显示
        pageControl.hidden = indexPath.section == 0
    }
}

// MARK: - 扩展CZEmoticonKeyboard  实现 CZEmoticonPageCellDelegate
extension CZEmoticonKeyboard: CZEmoticonPageCellDelegate {
    func pageCellEmoticonButtonClick(button: CZEmoticonButton) {
//        print("我在keyboard里面监听到了cell里面的按钮被点击了: \(button.emoticon))")
        
        textView?.insertEmoticon(button.emoticon!)
        
        // 将点击的表情添加到 最近 这组
        CZEmoticonManager.sharedManager.addFavorate(button.emoticon!)
    }
    
    func pageCellDeleteButtonClick() {
        // 删除textView上面的内容
        textView?.deleteBackward()
    }
}
